﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
//using SerialPortHelperLib;
using DevExpress.LookAndFeel;
using System.Threading;
using System.Configuration;
using XChip_Common;
using XChipTool.Enties;
using BinAnalysisHelp;
using AdbService;

namespace XChipTool
{
    public partial class XChip_SDE : DevExpress.XtraEditors.XtraUserControl
    {
        public SerialPort sPortTemp;
        private bool isRead = false;
        private bool isWrite = false;
        private KeyEventArgs keyEnter = new KeyEventArgs(Keys.Enter);//用来手动触发文本框下发配置
        private addressregisterManager aBll;
        private List<addressregister> XChipSde;
        private string ColorOrGray = "Color";
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;  
        //记录是否使用I2C设备读写
        public bool m_open = false;

        // 使用服务定位器获取ADB服务
        private IAdbCommandService adbService = ServiceLocator.AdbCommandService;
        public XChip_SDE()
        {
            InitializeComponent();
        }
        public XChip_SDE(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            aBll = _aBll;
            XChipSde = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "sde" || c.Classify == "Common"));

            InitializeComponent();
        }
        private async Task<long> GetSDERegister(string nameType)
        {
            if (XChipSde.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
            {
                long var = await ReadRegisterAsync(XChipSde.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address);
                return var;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }
        private async Task SetSDERegister(addressregister model, ulong add, bool isCheck = true)
        {
            if (isRead) return;

            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetDnsRegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }
        }
        #region 点击get数据

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            var Mode_switchvalue = await GetSDERegister("colorisgray_mode_en");
            if (await GetSDERegister("Mode_switch_en") == 1)
            {
                Mode_switch_en.Checked = true;
                if ((Mode_switchvalue & 0x80) == 0x80)
                {
                    Mode_switch.SelectedIndex = 1;
                }
                else
                {
                    Mode_switch.SelectedIndex = 0;
                }
                Mode_switch.Enabled = true;
            }
            else
            {
                Mode_switch.SelectedIndex = 0;
                Mode_switch.Enabled = false;
                Mode_switch_en.Checked = false;
                //下发一下对应寄存器
                if (isRead) return;
                if (XChipSde.Exists(c => c.NameType.ToLower() == ("colorisgray_mode_en").ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == ("colorisgray_mode_en").ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    SetSDERegister(model, Val);
                }
            }
            //WaitBefore.Start("读取中", "正在加载中", 10);
            foreach (Control item in this.Controls)
            {
                if (item is TextEdit)
                {
                    item.Text = string.Empty;
                }
            }
            isRead = true;

            //var iqmodel = XChipSde.Find(c => c.NameType.ToLower().Contains("iqsw") && c.ControlType == "1");
            //var iqVal = SerialSend.ReadRegister(Convert.ToUInt32(iqmodel.Address, 16), sPortTemp).ToString("X");
            //IQSW_en.Checked = BitsHelp.GetBitsCheckedToBool(iqmodel.Bits, iqmodel.Hex, iqVal) == 0;
            IQSW_en.Checked = await GetSDERegister("IQSW") == 7;
            string nameType = string.Empty;
            List<string> NameList = new List<string>();
            NameList.Add("IQSW_en");
            // 记录开始时间和寄存器计数
            var startTime = DateTime.Now;
            int totalRegisterCount = 0;
            for (int i = 0; i < XChipSde.Count; i++)
            {
                string type = "";
                if (XChipSde[i].NameType == "Ybright" || XChipSde[i].NameType.ToLower().Contains("blc_sub_ch") && !XChipSde[i].NameType.ToLower().Contains("list") 
                            )
                {

                }

                if (XChipSde[i].NameType.ToLower().Contains("mod_shift_".ToLower()) || XChipSde[i].NameType.ToLower().Contains("coef_".ToLower()))
                {
                    type = XChipSde[i].NameType;
                }
                else
                {
                    type = AppHelper.NameTypeToString(XChipSde[i].NameType);
                }

                if (type == "ybright_en")
                {
                    continue;
                }
                if (NameList.Exists(c => c == (type)))
                {
                    continue;
                }
                try
                {

                    var col = Controls_Find(type);
                    foreach (var item in col)
                    {
                        //需要修改，之前是用模糊查询
                        if (item is TextEdit)
                        {

                            var nList = XChipSde.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.NameType.ToLower().Contains(ColorOrGray.ToLower()) && c.ControlType == "0" && !c.NameType.ToLower().Contains("usb")).ToList();
                            if (nList.Count == 0)
                            {
                                nList = XChipSde.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            }
                            if (nList.Count == 1)
                            {
                                // 单个寄存器读取
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                            }
                            else if (item.Name == "Sat_u" || item.Name == "Sat_v" || item.Name == "Contrast" || item.Name == "Ybright" || item.Name.Contains("sat_vlist") || item.Name.Contains("sat_ulist") || item.Name.Contains("BLC_sub_ch") || item.Name.Contains("BLC_add_ch"))
                            {
                                nList = XChipSde.Where(c => c.NameType.ToLower() == (item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                                if (nList.Count() == 1)
                                {
                                    // 单个寄存器读取
                                    var address = nList[0].Address;
                                    totalRegisterCount++;
                                    await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                                }
                            }
                            else
                            {
                                //过滤两种模式
                                if (nList.Exists(c => c.NameType.ToLower().Contains("_color")) || nList.Exists(c => c.NameType.ToLower().Contains("_gray")))
                                {
                                    if (nList.Where(c => c.NameType.ToLower().Contains(ColorOrGray.ToLower())).ToList().Count > 0)
                                    {
                                        nList = nList.Where(c => c.NameType.ToLower().Contains(ColorOrGray.ToLower())).ToList();
                                        if (nList.Count == 1)
                                        {
                                            // 单个寄存器读取
                                            var address = nList[0].Address;
                                            totalRegisterCount++;
                                            await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                                        }
                                    }
                                }
                                // 多个寄存器组合读取
                                totalRegisterCount += nList.Count;
                                await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit);
                            }
                        }
                        else if (item is CheckEdit)
                        {
                            var nList = XChipSde.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                            if (nList.Count == 1)
                            {
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                            }
                        }


                    }

                    NameList.Add(type);
                }
                catch (Exception ex)
                {
                    continue;
                }
            }
            if (await GetSDERegister("TVE_UV_CTRL_en") == 1)
            {
                TVE_UV_CTRL_en.Checked = true;
                TVE_U_Backup.Enabled = true;
                TVE_V_Backup.Enabled = true;
            }
            else
            {
                TVE_UV_CTRL_en.Checked = false;
                TVE_U_Backup.Enabled = false;
                TVE_V_Backup.Enabled = false;
            }

            isRead = false;
            //WaitBefore.Close();
            EnShowHide();
        }

        #endregion



        private  Control[] Controls_Find(string type)
        {
            //var t =   this.Controls.Find(type, true);
            Control[] listc = new Control[100];
            System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            for (int i = 0; i < fieldInfo.Length; i++)
            {
                if (fieldInfo[i].Name.ToLower() == type.ToLower())
                {
                    listc =   this.Controls.Find(fieldInfo[i].Name, true);
                    break;
                }
            }
            return listc;
        }

        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            if (isWrite) return;

            if (XChipSde.Exists(c => c.NameType.ToLower() == $"{get_Current.Name}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"{get_Current.Name}".ToLower());
                get_Current.Text = (await GetSDERegister(model.NameType)).ToString("X2");
            }
        }
        #region 显示隐藏文件

        void IQSW_ShowHide(bool isbool)
        {
            Sat_u.Enabled = !isbool;
            Sat_v.Enabled = !isbool;
            Contrast.Enabled = !isbool;
            Ybright.Enabled = !isbool;
            BLC_sub_ch0.Enabled = !isbool;
            BLC_sub_ch1.Enabled = !isbool;
            BLC_sub_ch2.Enabled = !isbool;
            BLC_sub_ch3.Enabled = !isbool;

            BLC_add_ch0.Enabled = !isbool;
            BLC_add_ch1.Enabled = !isbool;
            BLC_add_ch2.Enabled = !isbool;
            BLC_add_ch3.Enabled = !isbool;

            sat_ulist0.Enabled = isbool;
            sat_ulist1.Enabled = isbool;
            sat_ulist2.Enabled = isbool;
            sat_ulist3.Enabled = isbool;
            sat_ulist4.Enabled = isbool;
            sat_ulist5.Enabled = isbool;
            sat_ulist6.Enabled = isbool;
            sat_ulist7.Enabled = isbool;
            sat_ulist8.Enabled = isbool;

            sat_vlist0.Enabled = isbool;
            sat_vlist1.Enabled = isbool;
            sat_vlist2.Enabled = isbool;
            sat_vlist3.Enabled = isbool;
            sat_vlist4.Enabled = isbool;
            sat_vlist5.Enabled = isbool;
            sat_vlist6.Enabled = isbool;
            sat_vlist7.Enabled = isbool;
            sat_vlist8.Enabled = isbool;


            contrastlist0.Enabled = isbool;
            contrastlist1.Enabled = isbool;
            contrastlist2.Enabled = isbool;
            contrastlist3.Enabled = isbool;
            contrastlist4.Enabled = isbool;
            contrastlist5.Enabled = isbool;
            contrastlist6.Enabled = isbool;
            contrastlist7.Enabled = isbool;
            contrastlist8.Enabled = isbool;


            ybrightlist0.Enabled = isbool;
            ybrightlist1.Enabled = isbool;
            ybrightlist2.Enabled = isbool;
            ybrightlist3.Enabled = isbool;
            ybrightlist4.Enabled = isbool;
            ybrightlist5.Enabled = isbool;
            ybrightlist6.Enabled = isbool;
            ybrightlist7.Enabled = isbool;
            ybrightlist8.Enabled = isbool;


            sensor_blc_ch0_list0.Enabled = isbool;
            sensor_blc_ch0_list1.Enabled = isbool;
            sensor_blc_ch0_list2.Enabled = isbool;
            sensor_blc_ch0_list3.Enabled = isbool;
            sensor_blc_ch0_list4.Enabled = isbool;
            sensor_blc_ch0_list5.Enabled = isbool;
            sensor_blc_ch0_list6.Enabled = isbool;
            sensor_blc_ch0_list7.Enabled = isbool;
            sensor_blc_ch0_list8.Enabled = isbool;

            blc_sub_ch0_list0.Enabled = isbool;
            blc_sub_ch1_list0.Enabled = isbool;
            blc_sub_ch2_list0.Enabled = isbool;
            blc_sub_ch3_list0.Enabled = isbool;

            blc_sub_ch0_list1.Enabled = isbool;
            blc_sub_ch1_list1.Enabled = isbool;
            blc_sub_ch2_list1.Enabled = isbool;
            blc_sub_ch3_list1.Enabled = isbool;

            blc_sub_ch0_list2.Enabled = isbool;
            blc_sub_ch1_list2.Enabled = isbool;
            blc_sub_ch2_list2.Enabled = isbool;
            blc_sub_ch3_list2.Enabled = isbool;

            blc_sub_ch0_list3.Enabled = isbool;
            blc_sub_ch1_list3.Enabled = isbool;
            blc_sub_ch2_list3.Enabled = isbool;
            blc_sub_ch3_list3.Enabled = isbool;

            blc_sub_ch0_list4.Enabled = isbool;
            blc_sub_ch1_list4.Enabled = isbool;
            blc_sub_ch2_list4.Enabled = isbool;
            blc_sub_ch3_list4.Enabled = isbool;

            blc_sub_ch0_list5.Enabled = isbool;
            blc_sub_ch1_list5.Enabled = isbool;
            blc_sub_ch2_list5.Enabled = isbool;
            blc_sub_ch3_list5.Enabled = isbool;

            blc_sub_ch0_list6.Enabled = isbool;
            blc_sub_ch1_list6.Enabled = isbool;
            blc_sub_ch2_list6.Enabled = isbool;
            blc_sub_ch3_list6.Enabled = isbool;

            blc_sub_ch0_list7.Enabled = isbool;
            blc_sub_ch1_list7.Enabled = isbool;
            blc_sub_ch2_list7.Enabled = isbool;
            blc_sub_ch3_list7.Enabled = isbool;

            blc_sub_ch0_list8.Enabled = isbool;
            blc_sub_ch1_list8.Enabled = isbool;
            blc_sub_ch2_list8.Enabled = isbool;
            blc_sub_ch3_list8.Enabled = isbool;



            blc_add_ch0_list0.Enabled = isbool;
            blc_add_ch1_list0.Enabled = isbool;
            blc_add_ch2_list0.Enabled = isbool;
            blc_add_ch3_list0.Enabled = isbool;

            blc_add_ch0_list1.Enabled = isbool;
            blc_add_ch1_list1.Enabled = isbool;
            blc_add_ch2_list1.Enabled = isbool;
            blc_add_ch3_list1.Enabled = isbool;

            blc_add_ch0_list2.Enabled = isbool;
            blc_add_ch1_list2.Enabled = isbool;
            blc_add_ch2_list2.Enabled = isbool;
            blc_add_ch3_list2.Enabled = isbool;

            blc_add_ch0_list3.Enabled = isbool;
            blc_add_ch1_list3.Enabled = isbool;
            blc_add_ch2_list3.Enabled = isbool;
            blc_add_ch3_list3.Enabled = isbool;

            blc_add_ch0_list4.Enabled = isbool;
            blc_add_ch1_list4.Enabled = isbool;
            blc_add_ch2_list4.Enabled = isbool;
            blc_add_ch3_list4.Enabled = isbool;

            blc_add_ch0_list5.Enabled = isbool;
            blc_add_ch1_list5.Enabled = isbool;
            blc_add_ch2_list5.Enabled = isbool;
            blc_add_ch3_list5.Enabled = isbool;

            blc_add_ch0_list6.Enabled = isbool;
            blc_add_ch1_list6.Enabled = isbool;
            blc_add_ch2_list6.Enabled = isbool;
            blc_add_ch3_list6.Enabled = isbool;

            blc_add_ch0_list7.Enabled = isbool;
            blc_add_ch1_list7.Enabled = isbool;
            blc_add_ch2_list7.Enabled = isbool;
            blc_add_ch3_list7.Enabled = isbool;

            blc_add_ch0_list8.Enabled = isbool;
            blc_add_ch1_list8.Enabled = isbool;
            blc_add_ch2_list8.Enabled = isbool;
            blc_add_ch3_list8.Enabled = isbool;

        }

        #endregion


        #region changed勾选框
        

        private async void SDE_IQSW_EN_CheckedChanged(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (isRead) return;
            //var readVal = GetSDERegister("nSwitchMode");
            //IQSW_ShowHide(IQSW_en.Checked);
            //SetSDERegister("nSwitchMode", (ulong)(IQSW_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            var chk = sender as CheckEdit;
            if (isRead) return;
           
            if (chk.Checked)
            {
                if (XChipSde.Exists(c => c.NameType.ToLower() == chk.Name.Replace("_en", "").ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == chk.Name.Replace("_en", "").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "7");
                    SetSDERegister(model, Val);
                }
                await WriteRegisterAsync(0x20000064.ToString("X"), 0x12.ToString("X"));
            }
            else
            {
                if (XChipSde.Exists(c => c.NameType.ToLower() == chk.Name.Replace("_en", "").ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == chk.Name.Replace("_en", "").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "0");
                    SetSDERegister(model, Val);
                }
                await WriteRegisterAsync(0x20000064.ToString("X"), 0x00.ToString("X"));
            }
            EnShowHide();
        }

        #endregion

        private void SDE_SATU_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            //SetSDERegister("SDE_SATU", (ulong)Convert.ToInt32(txtedit.Text, 16));
            if (XChipSde.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == txtedit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
        }

        private void SDE_SATV_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            //SetSDERegister("SDE_SATV", (ulong)Convert.ToInt32(txtedit.Text, 16));
            if (XChipSde.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == txtedit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
        }

        private void SDE_CONTRAST_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;

            if (XChipSde.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == txtedit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
        }

        private void SDE_YBRIGHT_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;

            if (XChipSde.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == txtedit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
        }

        private async void SDE_IQSATU0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);
            if (XChipSde.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
            var OsdDateExist = await ReadRegisterAsync("200011f3");
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1" || OsdDateExist == 0x1)
            {
                if (XChipSde.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}_usb".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"{txtedit.Name}_usb".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                    SetSDERegister(model, Val);
                }
            }



        }

        private void SDE_IQSATV0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);



            if (XChipSde.Exists(c => c.NameType.ToLower() == $"sat_v_day_{txtedit.Tag.ToString()}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"sat_v_day_{txtedit.Tag.ToString()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
            if (XChipSde.Exists(c => c.NameType.ToLower() == $"sat_v_night_{txtedit.Tag.ToString()}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"sat_v_night_{txtedit.Tag.ToString()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
            if (XChipSde.Exists(c => c.NameType.ToLower() == $"sat_v_day_set_{txtedit.Tag.ToString()}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"sat_v_day_set_{txtedit.Tag.ToString()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
            if (XChipSde.Exists(c => c.NameType.ToLower() == $"sat_v_night_set_{txtedit.Tag.ToString()}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"sat_v_night_set_{txtedit.Tag.ToString()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
            
        }

        private void SDE_IQCONTRAST0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);


            if (XChipSde.Exists(c => c.NameType.ToLower() == $"contrast_day_{txtedit.Tag.ToString()}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"contrast_day_{txtedit.Tag.ToString()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
            if (XChipSde.Exists(c => c.NameType.ToLower() == $"contrast_night_{txtedit.Tag.ToString()}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"contrast_night_{txtedit.Tag.ToString()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
            if (XChipSde.Exists(c => c.NameType.ToLower() == $"contrast_day_set_{txtedit.Tag.ToString()}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"contrast_day_set_{txtedit.Tag.ToString()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
            if (XChipSde.Exists(c => c.NameType.ToLower() == $"contrast_night_set_{txtedit.Tag.ToString()}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"contrast_night_set_{txtedit.Tag.ToString()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }


        }

        private void SDE_IQYBRIGHT0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);

            if (XChipSde.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
           
           
          
        }

        private void SDE_IQSENSORBLC0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);


            if (XChipSde.Exists(c => c.NameType.ToLower() == $"snr_BLC_day_{txtedit.Tag.ToString()}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"snr_BLC_day_{txtedit.Tag.ToString()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
            if (XChipSde.Exists(c => c.NameType.ToLower() == $"snr_BLC_night_{txtedit.Tag.ToString()}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"snr_BLC_night_{txtedit.Tag.ToString()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
           
        }


        private void SDE_WHITELEVEL_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);


            if (XChipSde.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
        }

        private void SDE_NORMLEVEL_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);


            if (XChipSde.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
        }

        private void SDE_BLANKLEVEL_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);


            if (XChipSde.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
        }

        private void SDE_SYNCLEVEL_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);


            if (XChipSde.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
        }

        private void SDE_BURSTLEVEL_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);


            if (XChipSde.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
        }

        private void SDE_MODSHIFTH_Leave(object sender, EventArgs e)
        {

            //var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            //if (isWrite) return;

            //if (string.IsNullOrEmpty(txtedit.Text)) return;
            //switch (txtedit.Tag.ToString())
            //{
            //    //case "0": SetSDERegister("SDE_MODSHIFTH", (ulong)Convert.ToInt32(txtedit.Text, 16)); break;
            //    //case "1": SetSDERegister("SDE_MODSHIFTM", (ulong)Convert.ToInt32(txtedit.Text, 16)); break;
            //    //case "2": SetSDERegister("SDE_MODSHIFTL", (ulong)Convert.ToInt32(txtedit.Text, 16)); break;
            //    //default:
            //    //    break;
            //}
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (Convert.ToInt32(txt.Text,16)> 0xFF)
                {
                    txt.Text = "FF";
                }
                if (XChipSde.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }
            }
        }

        private void SDE_SCHUE_Leave(object sender, EventArgs e)
        {

            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);


            if (XChipSde.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
        }

        private void SDE_COEFY_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);


            if (XChipSde.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"{txtedit.Name}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
        }

        private void SDE_SATU_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_SATU_Leave(sender, null);
            }
        }

        private void SDE_SATV_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_SATV_Leave(sender, null);
            }
        }

        private void SDE_CONTRAST_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_CONTRAST_Leave(sender, null);
            }
        }

        private void SDE_YBRIGHT_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_YBRIGHT_Leave(sender, null);
            }
        }

        private void SDE_WHITELEVEL_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_WHITELEVEL_Leave(sender, null);
            }
        }

        private void SDE_NORMLEVEL_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_NORMLEVEL_Leave(sender, null);
            }
        }

        private void SDE_BLANKLEVEL_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_BLANKLEVEL_Leave(sender, null);
            }
        }

        private void SDE_SYNCLEVEL_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_SYNCLEVEL_Leave(sender, null);
            }
        }

        private void SDE_BURSTLEVEL_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_BURSTLEVEL_Leave(sender, null);
            }
        }

        private void SDE_SCHUE_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_SCHUE_Leave(sender, null);
            }
        }

        private void SDE_COEFY_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_COEFY_Leave(sender, null);
            }
        }

        private void SDE_MODSHIFTH_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_MODSHIFTH_Leave(sender, null);
            }
        }

        private void SDE_IQSATU0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_IQSATU0_Leave(sender, null);
            }
        }

        private void SDE_IQSATV0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_IQSATV0_Leave(sender, null);
            }
        }

        private void SDE_IQCONTRAST0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_IQCONTRAST0_Leave(sender, null);
            }
        }

        private void SDE_IQYBRIGHT0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_IQYBRIGHT0_Leave(sender, null);
            }
        }

        private void SDE_IQSENSORBLC0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SDE_IQSENSORBLC0_Leave(sender, null);
            }
        }



        private void simpleButton6_Click(object sender, EventArgs e)
        {
            //string str = "       调节 SDE 模块中的饱和度/对比度/画面 Y 亮度/isp_BLC 值，其中 0x40 为基准饱和度，value＞0x40 则饱和度增强，value＜0x40 则饱和度降低；0x20 为基准对比度，value＞0x20 则对比度增强，value＜0x20 则对比度降低；Ybright 值越大，画面亮度越高。\r\n       勾选“IQSW”后 sat_u/sat_v/contrast/Ybright 的值根据设定的 gain 值以阶梯状形式或线性关系（0x80140264 bit[3]决定）进行映射至 SDE 模块中的相应寄存器地址中，调整后的值需画面亮度有 gain 值的变化（AE 收敛）后才能生效；点击“Get”可获取当前画面增益的 list 值。\r\n       TVE模块调节高清模拟输出模块中的载波幅值，建议配合 RX 量测波形进行调试。\r\n       更多详见《调试工具用户手册》。";
            Thread thread = new Thread(threadPro);
            thread.Start();
        }
        private void threadPro()

        {

            MethodInvoker methodInvoker = new MethodInvoker(ShowFormB);

            BeginInvoke(methodInvoker);

        }

        private void ShowFormB()

        {
            //string str = "\t      \t 调节 SDE 模块中的饱和度/对比度/画面 Y 亮度/isp_BLC 值，其中 0x40 为基准饱和度，value＞0x40 则饱和度增强，value＜0x40 则饱和度降低；0x20 为基准对比度，value＞0x20 则对比度增强，value＜0x20 则对比度降低；Ybright 值越大，画面亮度越高。\r\n"
            //    + "\t      \t 勾选“IQSW”后 sat_u/sat_v/contrast/Ybright 的值根据设定的 gain 值以阶梯状形式或线性关系（0x80140264 bit[3]决定）进行映射至 SDE 模块中的相应寄存器地址中，调整后的值点击“Refresh”后可立即生效；点击“Get”可获取当前画面增益的 list 值。\r\n"
            //    + "\t      \t 勾选“Mono_mode”可调整黑白模式下的效果参数，注意：只有在IR_cut模式或PWM调光模式下才能调节。\r\n"
            //    + "\t      \t TVE模块调节高清模拟输出模块中的载波幅值，建议配合 RX 量测波形进行调试。\r\n"
            //    + "\t      \t 更多详见《调试工具用户手册》。\r\n";
            string str = "";
            XChip_OptimizationTips ot = new XChip_OptimizationTips("SDE调优Tips", str);
            ot.StartPosition = FormStartPosition.CenterScreen;
            //ot.ShowDialog();
            ot.Show();

        }

        private void chk_Mono_mode_CheckedChanged(object sender, EventArgs e)
        {
            DayMonoSwitchLable(Mono_mode_en.Checked);
            if (isRead) return;
            var readVal = GetSDERegister("gray_en");
           
        }

        private void DayMonoSwitchLable(bool isMono)
        {
            if (isMono)
            {
                lbl_Sat_u.Text = lbl_Sat_u.Text.Replace("normal", "mono");
                lbl_Sat_v.Text = lbl_Sat_v.Text.Replace("normal", "mono");
                lbl_Contrast.Text = lbl_Contrast.Text.Replace("normal", "mono");
                lbl_Ybright.Text = lbl_Ybright.Text.Replace("normal", "mono");
                lbl_sensor_blc_ch0.Text = lbl_sensor_blc_ch0.Text.Replace("normal", "mono");
                lbl_blc_sub_ch0.Text = lbl_blc_sub_ch0.Text.Replace("normal", "mono");
                lbl_blc_sub_ch1.Text = lbl_blc_sub_ch1.Text.Replace("normal", "mono");
                lbl_blc_sub_ch2.Text = lbl_blc_sub_ch2.Text.Replace("normal", "mono");
                lbl_blc_sub_ch3.Text = lbl_blc_sub_ch3.Text.Replace("normal", "mono");
                lbl_blc_add_ch0.Text = lbl_blc_add_ch0.Text.Replace("normal", "mono");
                lbl_blc_add_ch1.Text = lbl_blc_add_ch1.Text.Replace("normal", "mono");
                lbl_blc_add_ch2.Text = lbl_blc_add_ch2.Text.Replace("normal", "mono");
                lbl_blc_add_ch3.Text = lbl_blc_add_ch3.Text.Replace("normal", "mono");
            }
            else
            {
                lbl_Sat_u.Text = lbl_Sat_u.Text.Replace("mono", "normal");
                lbl_Sat_v.Text = lbl_Sat_v.Text.Replace("mono", "normal");
                lbl_Contrast.Text = lbl_Contrast.Text.Replace("mono", "normal");
                lbl_Ybright.Text = lbl_Ybright.Text.Replace("mono", "normal");
                lbl_sensor_blc_ch0.Text = lbl_sensor_blc_ch0.Text.Replace("mono", "normal");
                lbl_blc_sub_ch0.Text = lbl_blc_sub_ch0.Text.Replace("mono", "normal");
                lbl_blc_sub_ch1.Text = lbl_blc_sub_ch1.Text.Replace("mono", "normal");
                lbl_blc_sub_ch2.Text = lbl_blc_sub_ch2.Text.Replace("mono", "normal");
                lbl_blc_sub_ch3.Text = lbl_blc_sub_ch3.Text.Replace("mono", "normal");
                lbl_blc_add_ch0.Text = lbl_blc_add_ch0.Text.Replace("mono", "normal");
                lbl_blc_add_ch1.Text = lbl_blc_add_ch1.Text.Replace("mono", "normal");
                lbl_blc_add_ch2.Text = lbl_blc_add_ch2.Text.Replace("mono", "normal");
                lbl_blc_add_ch3.Text = lbl_blc_add_ch3.Text.Replace("mono", "normal");
            }
        }

        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            var model = XChipSde.Find(c => c.NameType.ToLower() == $"Refresh_0".ToLower());
            SetSDERegister(model, 0x01);
            model = XChipSde.Find(c => c.NameType.ToLower() == $"Refresh_1".ToLower());
            SetSDERegister(model, 0x01);
            model = XChipSde.Find(c => c.NameType.ToLower() == $"Refresh_2".ToLower());
            SetSDERegister(model, 0x01);
        }

        private void txt_BLC_sub_ch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextEdit txt = sender as TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                uint sendVal = Convert.ToUInt32(txt.Text, 16);
                if (XChipSde.Exists(c => c.NameType.ToLower() == $"BLC_sub_ch{txt.Tag.ToString()}".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"BLC_sub_ch{txt.Tag.ToString()}".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }
            }
        }

        private void txt_BLC_add_ch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextEdit txt = sender as TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                uint sendVal = Convert.ToUInt32(txt.Text, 16);

                if (XChipSde.Exists(c => c.NameType.ToLower() == $"BLC_add_ch{txt.Tag.ToString()}".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"BLC_add_ch{txt.Tag.ToString()}".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }

                //switch (txt.Name)
                //{
                //    case "BLC_add_ch0":
                //        {
                //            blc_sub_ch0_list0.Text = txt.Text;
                //            //BLC_add_ch0.Text = txtedit.Text;
                //            //var model = XChipSde.Find(c => c.NameType.ToLower() == $"{BLC_add_ch0.Name}".ToLower());
                //            //var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                //            //SetSDERegister(model, Val);
                //        }
                //        break;

                //    case "BLC_add_ch1":
                //        {
                //            blc_sub_ch1_list0.Text = txt.Text;
                //            //BLC_add_ch1.Text = txtedit.Text;
                //            //var model = XChipSde.Find(c => c.NameType.ToLower() == $"{BLC_add_ch1.Name}".ToLower());
                //            //var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                //            //SetSDERegister(model, Val);
                //        }
                //        break;
                //    case "BLC_add_ch2":
                //        {
                //            blc_sub_ch2_list0.Text = txt.Text;
                //            //BLC_add_ch2.Text = txtedit.Text;
                //            //var model = XChipSde.Find(c => c.NameType.ToLower() == $"{BLC_add_ch2.Name}".ToLower());
                //            //var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                //            //SetSDERegister(model, Val);
                //        }

                //        break;
                //    case "BLC_add_ch3":
                //        {
                //            blc_sub_ch3_list0.Text = txt.Text;
                //            //BLC_add_ch3.Text = txtedit.Text;
                //            //var model = XChipSde.Find(c => c.NameType.ToLower() == $"{BLC_add_ch3.Name}".ToLower());
                //            //var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                //            //SetSDERegister(model, Val);
                //        }
                //        break;
                //    default:
                //        break;
                //}
            }
        }

        private void txt_blc_sub_ch0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextEdit txt = sender as TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                uint sendVal = Convert.ToUInt32(txt.Text, 16);

                if (Mode_switch_en.Checked)
                {
                    txt_blc_add_ch0_KeyDown(sender, e);
                }

                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_SUB_day_{txt.Tag.ToString()}_0".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_SUB_day_{txt.Tag.ToString()}_0".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }
                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_SUB_night_{txt.Tag.ToString()}_0".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_SUB_night_{txt.Tag.ToString()}_0".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }

                //if (isWrite) return;
                //if (null != sPortTemp && sPortTemp.IsOpen)
                //{
                //    if (isRead) return;
                //    var txt = sender as DevExpress.XtraEditors.TextEdit;
                //    if (string.IsNullOrEmpty(txt.Text)) return;
                //    if (XChipSde.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                //    {
                //        var model = XChipSde.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                //        SetSDERegister(model, Val);
                //    }
                //}

                
            }
        }
        private void txt_blc_sub_ch0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_blc_sub_ch0_KeyDown(sender, keyEnter);
        }
        private void txt_blc_sub_ch1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextEdit txt = sender as TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                uint sendVal = Convert.ToUInt32(txt.Text, 16);

                if (Mode_switch_en.Checked)
                {
                    txt_blc_add_ch1_KeyDown(sender, e);
                }
              
                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_SUB_day_{txt.Tag.ToString()}_1".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_SUB_day_{txt.Tag.ToString()}_1".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }
                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_SUB_night_{txt.Tag.ToString()}_1".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_SUB_night_{txt.Tag.ToString()}_1".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }

                //if (false) // (chk_Mono_mode.Enabled)
                //{
                //    string scenesMask = chk_Mono_mode.Checked ? "night" : "day";
                //    SetSDERegister($"ISP_BLC_SUB_{scenesMask}_{txt.Tag.ToString()}_1", sendVal);
                //}
                //else
                //{
                //    if (blc_sub_mode.Checked)
                //    {
                //        txt_blc_add_ch1_KeyDown(sender, e);
                //    }
                //    SetSDERegister($"ISP_BLC_SUB_day_{txt.Tag.ToString()}_1", sendVal);
                //    SetSDERegister($"ISP_BLC_SUB_night_{txt.Tag.ToString()}_1", sendVal);
                //}
            }
        }
        private void txt_blc_sub_ch1_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_blc_sub_ch1_KeyDown(sender, keyEnter);
        }
        private void txt_blc_sub_ch2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextEdit txt = sender as TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                uint sendVal = Convert.ToUInt32(txt.Text, 16);

                if (Mode_switch_en.Checked)
                {
                    txt_blc_add_ch2_KeyDown(sender, e);
                }

                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_SUB_day_{txt.Tag.ToString()}_2".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_SUB_day_{txt.Tag.ToString()}_2".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }
                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_SUB_night_{txt.Tag.ToString()}_2".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_SUB_night_{txt.Tag.ToString()}_2".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }

                //if (isWrite) return;
                //if (null != sPortTemp && sPortTemp.IsOpen)
                //{
                //    if (isRead) return;
                //    var txt = sender as DevExpress.XtraEditors.TextEdit;
                //    if (string.IsNullOrEmpty(txt.Text)) return;
                //    if (XChipSde.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                //    {
                //        var model = XChipSde.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                //        SetSDERegister(model, Val);
                //    }
                //}
                
            }
        }
        private void txt_blc_sub_ch2_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_blc_sub_ch2_KeyDown(sender, keyEnter);
        }
        private void txt_blc_sub_ch3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextEdit txt = sender as TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                uint sendVal = Convert.ToUInt32(txt.Text, 16);

                if (Mode_switch_en.Checked)
                {
                    txt_blc_add_ch3_KeyDown(sender, e);
                }

                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_SUB_day_{txt.Tag.ToString()}_3".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_SUB_day_{txt.Tag.ToString()}_3".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }
                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_SUB_night_{txt.Tag.ToString()}_3".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_SUB_night_{txt.Tag.ToString()}_3".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }

                //if (isWrite) return;
                //if (null != sPortTemp && sPortTemp.IsOpen)
                //{
                //    if (isRead) return;
                //    var txt = sender as DevExpress.XtraEditors.TextEdit;
                //    if (string.IsNullOrEmpty(txt.Text)) return;
                //    if (XChipSde.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                //    {
                //        var model = XChipSde.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                //        SetSDERegister(model, Val);
                //    }
                //}

               
            }
        }
        private void txt_blc_sub_ch3_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_blc_sub_ch3_KeyDown(sender, keyEnter);
        }
        private void txt_blc_add_ch0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextEdit txt = sender as TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                uint sendVal = Convert.ToUInt32(txt.Text, 16);


                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_ADD_day_{txt.Tag.ToString()}_0".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_ADD_day_{txt.Tag.ToString()}_0".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }
                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_ADD_night_{txt.Tag.ToString()}_0".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_ADD_night_{txt.Tag.ToString()}_0".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }


                //if (isWrite) return;
                //if (null != sPortTemp && sPortTemp.IsOpen)
                //{
                //    if (isRead) return;
                //    var txt = sender as DevExpress.XtraEditors.TextEdit;
                //    if (string.IsNullOrEmpty(txt.Text)) return;
                //    if (XChipSde.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                //    {
                //        var model = XChipSde.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                //        SetSDERegister(model, Val);
                //    }
                //}

            }
        }
        private void txt_blc_add_ch0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_blc_add_ch0_KeyDown(sender, keyEnter);
        }
        private void txt_blc_add_ch1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextEdit txt = sender as TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                uint sendVal = Convert.ToUInt32(txt.Text, 16);


                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_ADD_day_{txt.Tag.ToString()}_1".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_ADD_day_{txt.Tag.ToString()}_1".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }
                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_ADD_night_{txt.Tag.ToString()}_1".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_ADD_night_{txt.Tag.ToString()}_1".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }


                //if (isWrite) return;
                //if (null != sPortTemp && sPortTemp.IsOpen)
                //{
                //    if (isRead) return;
                //    var txt = sender as DevExpress.XtraEditors.TextEdit;
                //    if (string.IsNullOrEmpty(txt.Text)) return;
                //    if (XChipSde.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                //    {
                //        var model = XChipSde.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                //        SetSDERegister(model, Val);
                //    }
                //}

            }
        }
        private void txt_blc_add_ch1_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_blc_add_ch1_KeyDown(sender, keyEnter);
        }
        private void txt_blc_add_ch2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextEdit txt = sender as TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                uint sendVal = Convert.ToUInt32(txt.Text, 16);


                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_ADD_day_{txt.Tag.ToString()}_2".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_ADD_day_{txt.Tag.ToString()}_2".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }
                if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_ADD_night_{txt.Tag.ToString()}_2".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_ADD_night_{txt.Tag.ToString()}_2".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetSDERegister(model, Val);
                }


                //if (isWrite) return;
                //if (null != sPortTemp && sPortTemp.IsOpen)
                //{
                //    if (isRead) return;
                //    var txt = sender as DevExpress.XtraEditors.TextEdit;
                //    if (string.IsNullOrEmpty(txt.Text)) return;
                //    if (XChipSde.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                //    {
                //        var model = XChipSde.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                //        SetSDERegister(model, Val);
                //    }
                //}

            }
        }
        private void txt_blc_add_ch2_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_blc_add_ch2_KeyDown(sender, keyEnter);
        }
        private void txt_blc_add_ch3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextEdit txt = sender as TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                uint sendVal = Convert.ToUInt32(txt.Text, 16);
                if (false)// (chk_Mono_mode.Enabled)
                {
                    //string scenesMask = chk_Mono_mode.Checked ? "night" : "day";
                    //SetSDERegister($"ISP_BLC_ADD_{scenesMask}_{txt.Tag.ToString()}_3", sendVal);
                }
                else
                {

                    if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_ADD_day_{txt.Tag.ToString()}_3".ToLower()))
                    {
                        var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_ADD_day_{txt.Tag.ToString()}_3".ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetSDERegister(model, Val);
                    }
                    if (XChipSde.Exists(c => c.NameType.ToLower() == $"ISP_BLC_ADD_night_{txt.Tag.ToString()}_3".ToLower()))
                    {
                        var model = XChipSde.Find(c => c.NameType.ToLower() == $"ISP_BLC_ADD_night_{txt.Tag.ToString()}_3".ToLower());
                        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                        SetSDERegister(model, Val);
                    }
                }

                //if (isWrite) return;
                //if (null != sPortTemp && sPortTemp.IsOpen)
                //{
                //    if (isRead) return;
                //    var txt = sender as DevExpress.XtraEditors.TextEdit;
                //    if (string.IsNullOrEmpty(txt.Text)) return;
                //    if (XChipSde.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                //    {
                //        var model = XChipSde.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                //        SetSDERegister(model, Val);
                //    }
                //}

            }
        }
        private void txt_blc_add_ch3_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_blc_add_ch3_KeyDown(sender, keyEnter);
        }

        private void txt_BLC_sub_ch_0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_BLC_sub_ch_KeyDown(sender, keyEnter);
        }

        private void txt_BLC_add_ch_0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            txt_BLC_add_ch_KeyDown(sender, keyEnter);
        }

        private async void blc_sub_mode_CheckedChanged(object sender, EventArgs e)
        {
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            {
                panelControl3.Visible = Mode_switch_en.Checked;
                panelControl2.Visible = Mode_switch_en.Checked;
                var chk = sender as CheckEdit;
                if (isRead) return;
                if (XChipSde.Exists(c => c.NameType.ToLower() == (chk.Name).ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == (chk.Name).ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
                    SetSDERegister(model, Val);
                }
            }
            else
            {
                panelControl3.Visible = Mode_switch_en.Checked;
                var chk = sender as CheckEdit;
                if (!chk.Checked)
                {
                    Mode_switch.SelectedIndex = 0;
                    Mode_switch.Enabled = false;
                }
                else
                {
                    Mode_switch.Enabled = true;
                }
                if (isRead) return;
                if (XChipSde.Exists(c => c.NameType.ToLower() == (chk.Name).ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == (chk.Name).ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
                    SetSDERegister(model, Val);
                }
            }
            

        }
        private string GetConfigValue(string strKey)
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;

            return settings[strKey].Value;
        }
        private void XChip_SDE_Load(object sender, EventArgs e)
        {
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1" || GetConfigValue("ismipiout") == "1")
            {
                groupControl2.Visible = false;
            }
            else
            {
                groupControl2.Visible = true;
            }
            groupControl2.Visible = false;
            Task.Run(() => {
              
                this.Invoke((EventHandler)delegate {
                //if (ConfigurationManager.AppSettings["xcEdition"] == "1")
                //{
                //    groupControl2.Visible = false;
                //    labelControl35.Text = "饱和度_U";
                //    labelControl31.Text = "饱和度_V";
                //    labelControl34.Text = "对比度";
                //    labelControl30.Text = "亮度";

                //    labelControl5.Text = "黑电平加回";
                //    labelControl33.Text = "黑电平扣减";

                //    lbl_Sat_u.Text = "饱和度_U";
                //    lbl_Sat_v.Text = "饱和度_V";
                //    lbl_Contrast.Text = "对比度";
                //    lbl_Ybright.Text = "亮度";

                //    lbl_blc_sub_ch0.Text = "黑电平扣减_ch0";
                //    lbl_blc_sub_ch1.Text = "黑电平扣减_ch1";
                //    lbl_blc_sub_ch2.Text = "黑电平扣减_ch2";
                //    lbl_blc_sub_ch3.Text = "黑电平扣减_ch3";

                //    lbl_blc_add_ch0.Text = "黑电平加回_ch0";
                //    lbl_blc_add_ch1.Text = "黑电平加回_ch1";
                //    lbl_blc_add_ch2.Text = "黑电平加回_ch2";
                //    lbl_blc_add_ch3.Text = "黑电平加回_ch3";

                //    Mode_switch_en.Text = "黑电平加固模式";
                //    simpleButton2.Text = "获取";
                //    btn_Refresh.Text = "刷新";
                //    simpleButton1.Text = "获取参数";
                //    simpleButton6.Text = "调试指南";

                //    lbl_sensor_blc_ch0.Text = "黑电平_Sensor";
                //}
                for (int i = 0; i < XChipSde.Count; i++)
                {

                    var type = AppHelper.NameTypeToString(XChipSde[i].NameType);
                        //加上单选框的_en
                        if (XChipSde[i].ControlType == "1")
                        {
                            type = XChipSde[i].NameType;
                        }
                        try
                    {
                            var col = this.Controls.Find(type, true);


                            foreach (var item in col)
                            {
                                if (item is TextEdit)
                                {
                                    //声明一个SuerToolTip
                                    DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                                    //声明一个ToolTipTitleItem,保存标题
                                    DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                                    String tooltips = "";

                                    if (!string.IsNullOrEmpty(XChipSde[i].Bit_Wide))
                                    {
                                        tooltips += $"位宽={XChipSde[i].Bit_Wide}";
                                    }
                                    if (!string.IsNullOrEmpty(XChipSde[i].Bit_Accuracy))
                                    {
                                        tooltips += $"|精度={XChipSde[i].Bit_Accuracy}";
                                    }
                                    //设置标题文字
                                    toolTipTitleItem.Text = tooltips;
                                    //把标题添加到SuerToolTip
                                    graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                                    //指定控件的SuperTip
                                    ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                                    //正则判断
                                    ((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                                    ((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipSde[i].Bits, XChipSde[i].Bit_Wide, XChipSde.Where(c => c.NameType.ToLower().Contains(type) && c.ControlType == "0").Select(c => c.Bits).ToList());
                                }  
                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
               });
           });
            //Mode_switch_en.Checked = true;
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            
        //    SaveFileDialog sfd = new SaveFileDialog();
        //    //设置文件类型 
        //    sfd.Filter = "配置文件（*.txt）|*.txt";

        //    //设置默认文件类型显示顺序 
        //    sfd.FilterIndex = 1;

        //    //保存对话框是否记忆上次打开的目录 
        //    sfd.RestoreDirectory = true;
        //    sfd.FileName = "IQ_Setting_SDE_" + DateTime.Now.ToString("yyyyMMddHHmmss");
        //    if (sfd.ShowDialog() == DialogResult.OK)
        //    {
        //        var Pe_dal = new parameter_exportManager();
        //        if (null != Pe_dal)
        //        {
        //            WaitBefore.Start("参数导出", "正在加载中", 60);
                   
        //            var tempList = Pe_dal.GetListToExport().Where(c => c.Module.Contains("sat_u 0x80301701") || 
        //            c.Module.Contains("sat_v 0x80301702") ||
        //            c.Module.Contains("contrast 0x80301704") || 
        //            c.Module.Contains("ybright 0x80301707")||
        //            c.Module.Contains("isp_blc_sub 0x803000a0")||
        //            c.Module.Contains("isp_blc_add 0x803000b4")||
        //            c.Module.Contains("snr_blc_value")||
        //            c.Module == "BLC").OrderBy(c => c.SortNum).ToList();
        //            #region 判断是否需要用白天的数据
        //            var Pe_patch_dal = new parameter_export_patchManager();
        //            var patchList = Pe_patch_dal.GetList();
        //            var conditionList = tempList.Select(c => c.ConditionAddr).Distinct();
        //            foreach (var item in conditionList)
        //            {
        //                if (SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp) == 0)
        //                {
        //                    patchList.RemoveAll(c => c.ConditionAddr == item);
        //                }
        //            }
        //            #endregion
        //            var sb = XChipHelp.ReadParameterExportExpand(tempList, "80", patchList, sPortTemp);
        //            System.IO.File.WriteAllText(sfd.FileName, sb.ToString());

        //        }
        //        WaitBefore.Close();
        //        DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
        //    }
        }

        private void SDE_IQBLC10_4_Enter(object sender, EventArgs e)
        {

        }
        string tempTve = string.Empty;
        private void SDE_SCHUE_Enter(object sender, EventArgs e)
        {
            tempTve = (sender as TextEdit).Text;
        }

        private void SDE_WHITELEVEL_Enter(object sender, EventArgs e)
        {
            tempTve = (sender as TextEdit).Text;
        }

        private void SDE_NORMLEVEL_Enter(object sender, EventArgs e)
        {
            tempTve = (sender as TextEdit).Text;
        }

        private void SDE_BLANKLEVEL_Enter(object sender, EventArgs e)
        {
            tempTve = (sender as TextEdit).Text;
        }

        private void SDE_SYNCLEVEL_Enter(object sender, EventArgs e)
        {
            tempTve = (sender as TextEdit).Text;
        }

        private void SDE_MODSHIFTH_Enter(object sender, EventArgs e)
        {
            tempTve = (sender as TextEdit).Text;
        }

        private void SDE_COEFY_Enter(object sender, EventArgs e)
        {
            tempTve = (sender as TextEdit).Text;
        }

        private void SDE_BURSTLEVEL_Enter(object sender, EventArgs e)
        {
            tempTve = (sender as TextEdit).Text;
        }

        private void simpleButton1_MouseEnter(object sender, EventArgs e)
        {
            isWrite = true;
        }

        private void simpleButton1_MouseLeave(object sender, EventArgs e)
        {
            isWrite = false;
        }

        private async void btn_Get_scene_Click(object sender, EventArgs e)
        {
            List<string> listfiltration = new List<string> { "contrastlist0", "contrastlist1", "contrastlist2", "contrastlist3", "contrastlist4", "contrastlist5", "contrastlist6", "contrastlist7","contrastlist8",
                "ybrightlist0","ybrightlist1","ybrightlist2","ybrightlist3","ybrightlist4","ybrightlist5","ybrightlist6","ybrightlist7","ybrightlist8" };
            foreach (Control item in this.Controls)
            {
                
                if (item is TextEdit)
                {
                    //过滤掉指定寄存器
                    if (!listfiltration.Exists(c => c.Contains(item.Name.ToString())))
                    {
                        continue;
                    }
                    item.Text = string.Empty;
                }
            }
            isRead = true;
            var Mode_switchvalue =await GetSDERegister("colorisgray_mode_en");
            if (await GetSDERegister("Mode_switch_en") == 1)
            {
                Mode_switch_en.Checked = true;
                if ((Mode_switchvalue & 0x80) == 0x80)
                {
                    Mode_switch.SelectedIndex = 1;
                }
                else
                {
                    Mode_switch.SelectedIndex = 0;
                }
                Mode_switch.Enabled = true;
            }
            else
            {
                Mode_switch.SelectedIndex = 0;
                Mode_switch.Enabled = false;
                Mode_switch_en.Checked = false;
                //下发一下对应寄存器
                if (isRead) return;
                if (XChipSde.Exists(c => c.NameType.ToLower() == ("colorisgray_mode_en").ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == ("colorisgray_mode_en").ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    SetSDERegister(model, Val);
                }
            }
            UpdateColorGrayAddr();
        }

        public async void UpdateColorGrayAddr()
        {
            WaitBefore.Start("读取中", "正在加载中", 10);
            List<string> listfiltration = new List<string> { "contrastlist", "ybrightlist" };
            foreach (Control item in this.Controls)
            {

                if (item is TextEdit)
                {
                    //过滤掉指定寄存器
                    if (!item.Name.ToString().ToLower().Contains("contrastlist") && !item.Name.ToString().ToLower().Contains("ybrightlist"))
                    {
                        continue;
                    }
                    item.Text = string.Empty;
                }
            }
            isRead = true;
            string nameType = string.Empty;
            List<string> NameList = new List<string>();
            // 记录开始时间和寄存器计数
            var startTime = DateTime.Now;
            int totalRegisterCount = 0;
            for (int i = 0; i < XChipSde.Count; i++)
            {
                string type = "";
                if (XChipSde[i].NameType == "Sat_u" || XChipSde[i].NameType.ToLower().Contains("contrast")
                            || XChipSde[i].NameType.ToLower().Contains("ybright") || XChipSde[i].NameType.ToLower().Contains("ynr_scale_enhance"))
                {

                }

                if (XChipSde[i].NameType.ToLower().Contains("mod_shift_".ToLower()) || XChipSde[i].NameType.ToLower().Contains("coef_".ToLower()))
                {
                    type = XChipSde[i].NameType;
                }
                else
                {
                    type = AppHelper.NameTypeToString(XChipSde[i].NameType);
                }
                try
                {

                    var col = Controls_Find(type);
                    foreach (var item in col)
                    {
                        //需要修改，之前是用模糊查询
                        if (item is TextEdit)
                        {
                            if (!item.Name.ToString().ToLower().Contains("contrast") && !item.Name.ToString().ToLower().Contains("ybright"))
                            {
                                continue;
                            }
                            var nList = XChipSde.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.NameType.ToLower().Contains(ColorOrGray.ToLower()) && c.ControlType == "0" && !c.NameType.ToLower().Contains("usb")).ToList();
                            if (nList.Count == 0)
                            {
                                nList = XChipSde.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            }
                            if (nList.Count == 1)
                            {
                                // 单个寄存器读取
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                            }
                            else if (item.Name == "Sat_u" || item.Name == "Sat_v" || item.Name == "Contrast" || item.Name == "Ybright" || item.Name.Contains("sat_vlist") || item.Name.Contains("sat_ulist"))
                            {
                                nList = XChipSde.Where(c => c.NameType.ToLower() == (item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                                if (nList.Count() == 1)
                                {
                                    // 单个寄存器读取
                                    var address = nList[0].Address;
                                    totalRegisterCount++;
                                    await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                                }
                            }
                            else
                            {
                                //过滤两种模式
                                if (nList.Exists(c => c.NameType.ToLower().Contains("_color")) || nList.Exists(c => c.NameType.ToLower().Contains("_gray")))
                                {
                                    if (nList.Where(c => c.NameType.ToLower().Contains(ColorOrGray.ToLower())).ToList().Count > 0)
                                    {
                                        nList = nList.Where(c => c.NameType.ToLower().Contains(ColorOrGray.ToLower())).ToList();
                                        if (nList.Count == 1)
                                        {
                                            // 单个寄存器读取
                                            var address = nList[0].Address;
                                            totalRegisterCount++;
                                            await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                                        }
                                    }
                                }
                                // 多个寄存器组合读取
                                totalRegisterCount += nList.Count;
                                await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit);
                            }
                        }
                        else if (item is CheckEdit)
                        {
                            var nList = XChipSde.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                            if (nList.Count == 1)
                            {
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                            }
                        }


                    }
                    NameList.Add(type);
                }
                catch (Exception ex)
                {
                    continue;
                }
            }

            isRead = false;
            WaitBefore.Close();
        }
        private async void Mode_switch_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Mode_switch.EditValue.ToString() == "1")
            {
                ColorOrGray = "Color";
                if (isRead) return;
                if (XChipSde.Exists(c => c.NameType.ToLower() == ("colorisgray_mode_en").ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == ("colorisgray_mode_en").ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    SetSDERegister(model, Val);
                }
                lbl_Contrast.Text = "Contrast_Color";
                lbl_Ybright.Text = "Ybright_Color";
                UpdateColorGrayAddr();
            }
            else
            {
                ColorOrGray = "Gray";
                if (isRead) return;
                if (XChipSde.Exists(c => c.NameType.ToLower() == ("colorisgray_mode_en").ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == ("colorisgray_mode_en").ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), true);
                    SetSDERegister(model, Val);
                }
                lbl_Contrast.Text = "Contrast_Gray";
                lbl_Ybright.Text = "Ybright_Gray";
                UpdateColorGrayAddr();
            }
            
        }

        private async void contrastlist0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            uint sendVal = Convert.ToUInt32(txtedit.Text, 16);
            if (XChipSde.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}_{ColorOrGray}".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"{txtedit.Name}_{ColorOrGray}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetSDERegister(model, Val);
            }
            var OsdDateExist = await ReadRegisterAsync("200011f3");
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1" || OsdDateExist == 0x1)
            {
                if (XChipSde.Exists(c => c.NameType.ToLower() == $"{txtedit.Name}_{ColorOrGray}_usb".ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == $"{txtedit.Name}_{ColorOrGray}_usb".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                    SetSDERegister(model, Val);
                }
            }
                
        }

        private void contrastlist0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                contrastlist0_Leave(sender, null);
            }
        }

        private async void simpleButton3_Click(object sender, EventArgs e)
        {
            List<string> listfiltration = new List<string> { "BLC_sub_ch0","BLC_sub_ch1","BLC_sub_ch2","BLC_sub_ch3",
                "BLC_add_ch0","BLC_add_ch1","BLC_add_ch2","BLC_add_ch3",
                "Contrast", "Ybright", "Sat_u", "Sat_v" };

            var Mode_switchvalue =await GetSDERegister("colorisgray_mode_en");
            if (await GetSDERegister("Mode_switch_en") == 1)
            {
                Mode_switch_en.Checked = true;
                if ((Mode_switchvalue & 0x80) == 0x80)
                {
                    Mode_switch.SelectedIndex = 1;
                }
                else
                {
                    Mode_switch.SelectedIndex = 0;
                }
                Mode_switch.Enabled = true;
            }
            else
            {
                Mode_switch.SelectedIndex = 0;
                Mode_switch.Enabled = false;
                Mode_switch_en.Checked = false;
                //下发一下对应寄存器
                if (isRead) return;
                if (XChipSde.Exists(c => c.NameType.ToLower() == ("colorisgray_mode_en").ToLower()))
                {
                    var model = XChipSde.Find(c => c.NameType.ToLower() == ("colorisgray_mode_en").ToLower());
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    SetSDERegister(model, Val);
                }
            }
            WaitBefore.Start("读取中", "正在加载中", 10);
            foreach (Control item in this.Controls)
            {
                if (item is TextEdit)
                {
                    item.Text = string.Empty;
                }
            }
            isRead = true;

            string nameType = string.Empty;
            List<string> NameList = new List<string>();
            // 记录开始时间和寄存器计数
            var startTime = DateTime.Now;
            int totalRegisterCount = 0;
            for (int i = 0; i < XChipSde.Count; i++)
            {
                string type = "";
                if (XChipSde[i].NameType.ToLower().Contains("mod_shift_".ToLower()) || XChipSde[i].NameType.ToLower().Contains("coef_".ToLower()))
                {
                    type = XChipSde[i].NameType;
                }
                else
                {
                    type = AppHelper.NameTypeToString(XChipSde[i].NameType);
                }
                if (NameList.Exists(c => c == (type)))
                {
                    continue;
                }
                try
                {

                    var col = Controls_Find(type);
                    foreach (var item in col)
                    {
                        if (item == null || !listfiltration.Any(itemss => item.Name == (itemss)))
                        {
                            continue;
                        }

                        if (item is TextEdit)
                        {

                            var nList = XChipSde.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.NameType.ToLower().Contains(ColorOrGray.ToLower()) && c.ControlType == "0" && !c.NameType.ToLower().Contains("usb")).ToList();
                            if (nList.Count == 0)
                            {
                                nList = XChipSde.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            }
                            if (nList.Count == 1)
                            {
                                // 单个寄存器读取
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                            }
                            else if (item.Name == "Sat_u" || item.Name == "Sat_v" || item.Name == "Contrast" || item.Name == "Ybright" || item.Name.Contains("sat_vlist") || item.Name.Contains("sat_ulist") || item.Name.Contains("BLC_sub_ch") || item.Name.Contains("BLC_add_ch"))
                            {
                                nList = XChipSde.Where(c => c.NameType.ToLower() == (item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                                if (nList.Count() == 1)
                                {
                                    // 单个寄存器读取
                                    var address = nList[0].Address;
                                    totalRegisterCount++;
                                    await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                                }
                            }
                            else
                            {
                                //过滤两种模式
                                if (nList.Exists(c => c.NameType.ToLower().Contains("_color")) || nList.Exists(c => c.NameType.ToLower().Contains("_gray")))
                                {
                                    if (nList.Where(c => c.NameType.ToLower().Contains(ColorOrGray.ToLower())).ToList().Count > 0)
                                    {
                                        nList = nList.Where(c => c.NameType.ToLower().Contains(ColorOrGray.ToLower())).ToList();
                                        if (nList.Count == 1)
                                        {
                                            // 单个寄存器读取
                                            var address = nList[0].Address;
                                            totalRegisterCount++;
                                            await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                                        }
                                    }
                                }
                                // 多个寄存器组合读取
                                totalRegisterCount += nList.Count;
                                await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit);
                            }
                        }
                        else if (item is CheckEdit)
                        {
                            var nList = XChipSde.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                            if (nList.Count == 1)
                            {
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                            }
                        }
                    }
                    NameList.Add(type);
                }
                catch (Exception ex)
                {
                    continue;
                }             
            }
            isRead = false;
            WaitBefore.Close();
        }
        private void EnShowHide()
        {
            bool isbool = IQSW_en.Checked;
            foreach (Control control in groupControl1.Controls)
            {
                if (control is TextEdit)
                {
                    TextEdit textEdit = (TextEdit)control;
                    textEdit.Enabled = isbool;
                }
            }
            foreach (Control control in panelControl2.Controls)
            {
                if (control is TextEdit)
                {
                    TextEdit textEdit = (TextEdit)control;
                    textEdit.Enabled = isbool;
                }
            }
            foreach (Control control in blcpanelC.Controls)
            {
                if (control is TextEdit)
                {
                    TextEdit textEdit = (TextEdit)control;
                    textEdit.Enabled = isbool;
                }
            }
            foreach (Control control in panelControl3.Controls)
            {
                if (control is TextEdit)
                {
                    TextEdit textEdit = (TextEdit)control;
                    textEdit.Enabled = isbool;
                }
            }
            foreach (Control control in panelControl1.Controls)
            {
                if (control is TextEdit)
                {
                    TextEdit textEdit = (TextEdit)control;
                    textEdit.Enabled = !isbool;
                }
            }
            foreach (Control control in blc_add_panel.Controls)
            {
                if (control is TextEdit)
                {
                    TextEdit textEdit = (TextEdit)control;
                    textEdit.Enabled = !isbool;
                }
            }
            get_Current.Enabled = false;
        }

        private void TVE_UV_CTRL_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (XChipSde.Exists(c => c.NameType.ToLower() == $"TVE_UV_CTRL_en".ToLower()))
            {
                var model = XChipSde.Find(c => c.NameType.ToLower() == $"TVE_UV_CTRL_en".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, TVE_UV_CTRL_en.Checked ? "1" : "0");
                SetSDERegister(model, Val);
            }
            if (TVE_UV_CTRL_en.Checked)
            {
                TVE_U_Backup.Enabled = true;
                TVE_V_Backup.Enabled = true;
            }
            else
            {
                TVE_U_Backup.Enabled = false;
                TVE_V_Backup.Enabled = false;
            }
        }

        /// <summary>
        /// 异步读取单个寄存器并更新文本框
        /// </summary>
        private async Task ReadRegisterAndUpdateTextAsync(string address, TextEdit textEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");

                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    string processedValue = record.Values;
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    Console.WriteLine($"[ADBForm] 成功读取寄存器 {address} 值: {processedValue}");

                    // 处理位操作
                    string displayValue;
                    if (processedValue != "0")
                    {
                        var uintValue = BitsHelp.GetBitsToUint(bits, hex, processedValue);
                        displayValue = uintValue.ToString("X");
                        Console.WriteLine($"[ADBForm] 寄存器 {address} Bits处理后值: {displayValue} (bits:{bits}, hex:{hex})");
                    }
                    else
                    {
                        displayValue = "0";
                    }

                    // 更新UI
                    UpdateTextEdit(textEdit, displayValue);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    UpdateTextEdit(textEdit, "0");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 异步读取多个寄存器并组合更新文本框
        /// </summary>
        private async Task ReadMultipleRegistersAndUpdateTextAsync(List<addressregister> nList, TextEdit textEdit)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取多个寄存器，数量: {nList.Count}");

                string combinedValue = string.Empty;

                // 按预定义的优先级顺序读取寄存器
                var priorityOrder = new[] { "_h", "_m0", "_m1", "_m2", "_m3", "_l" };

                foreach (var priority in priorityOrder)
                {
                    addressregister register = FindRegisterByPriority(nList, priority);

                    if (register != null)
                    {
                        Console.WriteLine($"[ADBForm] 读取优先级 '{priority}' 的寄存器: {register.NameType} ({register.Address})");

                        // 发送读取命令
                        string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{register.Address},0,0\"";
                        adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{register.Address}");

                        // 等待命令执行
                        await Task.Delay(10);

                        // 获取寄存器值
                        var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(register.Address, "Read", 500));

                        if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                        {
                            string processedValue = record.Values;
                            if (processedValue.StartsWith("0x"))
                            {
                                processedValue = processedValue.Substring(2);
                            }

                            combinedValue += processedValue.PadLeft(2, '0');
                            Console.WriteLine($"[ADBForm] 成功读取 {register.Address}，当前组合值: {combinedValue}");
                        }
                        else
                        {
                            combinedValue += "00";
                            Console.WriteLine($"[ADBForm] 读取 {register.Address} 失败，使用默认值00，当前组合值: {combinedValue}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 未找到包含 '{priority}' 的寄存器");
                    }
                }

                Console.WriteLine($"[ADBForm] 最终组合值: {combinedValue}");

                // 更新UI
                UpdateTextEdit(textEdit, combinedValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取多个寄存器失败: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 根据优先级查找寄存器
        /// </summary>
        private addressregister FindRegisterByPriority(List<addressregister> nList, string priority)
        {
            if (priority == "_l")
            {
                // 特殊处理 _l 寄存器
                if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                {
                    // 首先查找以 "_l" 结尾的寄存器
                    var exactMatch = nList.Find(c => c.NameType.ToLower().EndsWith("_l"));
                    if (exactMatch != null)
                    {
                        Console.WriteLine($"[ADBForm] 找到以 '_l' 结尾的寄存器: {exactMatch.NameType}");
                        return exactMatch;
                    }
                    else
                    {
                        // 如果没有以 "_l" 结尾的，则使用最后一个包含 "_l" 的寄存器
                        var containsMatch = nList.Last(c => c.NameType.ToLower().Contains("_l"));
                        Console.WriteLine($"[ADBForm] 找到包含 '_l' 的寄存器: {containsMatch.NameType}");
                        return containsMatch;
                    }
                }
            }
            else
            {
                // 其他寄存器正常处理
                var register = nList.Find(c => c.NameType.ToLower().Contains(priority));
                if (register != null)
                {
                    Console.WriteLine($"[ADBForm] 找到包含 '{priority}' 的寄存器: {register.NameType}");
                    return register;
                }
            }

            return null;
        }

        /// <summary>
        /// 更新文本框的辅助方法
        /// </summary>
        private void UpdateTextEdit(TextEdit textEdit, string value)
        {
            if (textEdit.InvokeRequired)
            {
                textEdit.Invoke(new Action(() =>
                {
                    textEdit.Text = value;
                    Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
                }));
            }
            else
            {
                textEdit.Text = value;
                Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
            }
        }

        /// <summary>
        /// 异步读取寄存器并更新复选框
        /// </summary>
        private async Task ReadRegisterAndUpdateCheckAsync(string address, CheckEdit checkEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器并更新复选框: {address}");

                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                bool isChecked = false;
                if (!string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    isChecked = BitsHelp.GetBitsCheckedToBool(bits, hex, record.Values) == 0;
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值:{record.Values}, 状态:{isChecked}");
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值无效, 状态:false");
                }

                // 更新UI
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = isChecked));
                }
                else
                {
                    checkEdit.Checked = isChecked;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 更新复选框失败: {ex.Message}");
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = false));
                }
                else
                {
                    checkEdit.Checked = false;
                }
            }
        }

        /// <summary>
        /// 异步读取单个寄存器返回值
        /// </summary>
        private async Task<long> ReadRegisterAsync(string address)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");
                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    return Convert.ToInt32(record.Values, 16);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                return 0;
            }
        }
        /// <summary>
        /// 异步写入单个寄存器，在值不匹配时自动重试一次
        /// </summary>
        private async Task<bool> WriteRegisterAsync(string address, string value)
        {
            int maxRetries = 1; // 值不匹配时最多重试一次
            int retryCount = 0;

            while (retryCount <= maxRetries)
            {
                try
                {
                    if (retryCount > 0)
                    {
                        Console.WriteLine($"[ADBForm] 第 {retryCount} 次重试写入寄存器: {address} 值: {value}");
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 开始写入寄存器: {address} 值: {value}");
                    }

                    // 处理位操作（如果有）
                    string processedValue = value;

                    // 确保值是十六进制格式（不带0x前缀）
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    // 发送写入命令
                    string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"1,{address},{processedValue},0\"";
                    adbService.ExecuteAdbCommandAsync(adbCommand, $"写操作 - 地址:{address} 值:{processedValue}");

                    // 等待命令执行
                    await Task.Delay(10);

                    // 验证写入是否成功 - 等待写入记录出现
                    var writeRecord = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Write", 500));

                    if (writeRecord != null && !string.IsNullOrEmpty(writeRecord.Values))
                    {
                        string actualValue = writeRecord.Values;
                        if (actualValue.StartsWith("0x"))
                        {
                            actualValue = actualValue.Substring(2);
                        }

                        // 比较写入的值是否匹配
                        bool success = string.Equals(actualValue, processedValue, StringComparison.OrdinalIgnoreCase);

                        if (success)
                        {
                            Console.WriteLine($"[ADBForm] 成功写入寄存器 {address} 值: {processedValue}");
                            return true;
                        }
                        else
                        {
                            Console.WriteLine($"[ADBForm] 写入寄存器 {address} 值不匹配，期望: {processedValue}，实际: {actualValue}");

                            // 如果不匹配且还有重试次数，则继续重试
                            if (retryCount < maxRetries)
                            {
                                retryCount++;
                                Console.WriteLine($"[ADBForm] 准备重试写入...");
                                continue; // 直接进入下一次循环，重新发送命令
                            }
                            else
                            {
                                Console.WriteLine($"[ADBForm] 写入寄存器 {address} 重试次数已用完，仍然不匹配");
                                return false;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 写入寄存器 {address} 失败，未找到写入确认记录");

                        // 如果未找到记录且还有重试次数，则重试
                        if (retryCount < maxRetries)
                        {
                            retryCount++;
                            Console.WriteLine($"[ADBForm] 准备重试写入...");
                            continue;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ADBForm] 写入寄存器 {address} 异常: {ex.Message}");

                    // 如果异常且还有重试次数，则重试
                    if (retryCount < maxRetries)
                    {
                        retryCount++;
                        Console.WriteLine($"[ADBForm] 准备重试写入...");
                        await Task.Delay(10); // 异常后稍作延迟再重试
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return false; // 理论上不会执行到这里
        }
    }
}

